package us.wili.dev.client.controller;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import us.wili.dev.client.model.req.MiniGetUserInfoReq;
import us.wili.dev.client.model.rsp.MiniUserInfoRsp;
import us.wili.dev.client.service.ClientUserService;
import us.wili.dev.client.service.SmsService;
import us.wili.dev.common.model.ResponseDto;
import us.wili.dev.common.util.ResponseUtil;
import us.wili.dev.jwt.model.ChannelEnum;
import us.wili.dev.model.entity.User;


import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Validated
@RestController
@RequestMapping("/api/login")
@Api(tags = "登录注册接口")
public class LoginController {
    @Autowired
    private ClientUserService clientUserService;

    @PostMapping("/getMiniUserInfo")
    @ApiOperation("获取Openid")
    public ResponseDto<MiniUserInfoRsp> getUserInfo(@Valid @RequestBody MiniGetUserInfoReq req,javax.servlet.http.HttpServletRequest request,HttpServletResponse response) {
        WxMaJscode2SessionResult sessionInfo=clientUserService.getOpenidBycode(req);
        //userService.getOpenidBycode(req);
        //判断用户是否存在 如果是直接返回 如果不是保存进user表
        User user= clientUserService.isPhoneAlreadyBinding(sessionInfo);
        if (user==null){
            user = clientUserService.registe(sessionInfo);
            user= clientUserService.isPhoneAlreadyBinding(sessionInfo);
        }
        //查出对应user实体，传入 setToken方法保存JWT信息
        String token= clientUserService.setJwtToken(user, ChannelEnum.MINIAPP, request, response);
        MiniUserInfoRsp miniUserInfoRsp =clientUserService.setuser(sessionInfo,token,user);
        return ResponseUtil.getSuccessRsp(miniUserInfoRsp);
    }
}
